//
//  UserAccountViewModel.swift
//  WeiBo_One
//
//  Created by apple on 15/10/22.
//  Copyright © 2015年 蜡笔小炎. All rights reserved.
//

import Foundation

// 没有父类,不可以使用 KVC
class UserAccountViewModel {
    
    //创建单例
    static let sharedAccoutViewModel = UserAccountViewModel()
    
    //用户数据模型
    var account: UserAccount?
    
    //返回有效的 token
    var accountToken: String? {
        if !isExpires {
            return account?.access_token
        }
        return nil
    }
    
    //用户是否登录标记
    var userLogon: Bool {
        return (account?.access_token != nil) && !isExpires
    }
    
    //用户模型归档地址
    private var accountPath: String {
        let accountPath = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last!
        return (accountPath as NSString).stringByAppendingPathComponent("account.plist")
    }
    
    //账户Token是否过期
    private var isExpires: Bool {
        if account?.expires_Date?.compare(NSDate()) == NSComparisonResult.OrderedDescending {
            //降序，NSDate() > expires_Date
            return false
        }
        return true
    }
    
    private init() {
        //解档，并给account赋值
        account = NSKeyedUnarchiver.unarchiveObjectWithFile(accountPath) as? UserAccount
        //如果账号Token过期，清空账号，要求用户重新登录
        if isExpires {
            account = nil
        }
    }
}

//MARK: - 用户账户相关网络数据
extension UserAccountViewModel {// TODO: 重构中，未完成
    ///加载用户Token
    func loadAccoutToken(OAuthCode: String, finished: (isSuccess: Bool) -> ()) {
        
        // 用授权码换Token令牌
        NetWorkTools.sharedTools.loadAccessToken(oAuthCode: OAuthCode) { (result, error) -> () in
            // 如果error有值，打印并 return
            if error != nil {
                print(error)
                finished(isSuccess: false)
                return
            }
            
            // 得到用户uid和token
            self.account = UserAccount(dict: result as! Dictionary)
            // 获取用户信息
            self.loadUserInfo(self.account!,finished:finished)
        }
        
    }
    
    /// 加载用户的信息
    private func loadUserInfo(accout: UserAccount,finished: (isSuccess: Bool) -> ()) {
        NetWorkTools.sharedTools.loadAccoutInfo(accout.uid!, accout_token: accout.access_token!, finished: { (result, error) -> () in
            if error != nil {
                print("加载用户出错了")
                finished(isSuccess: false)
                return
            }
            
            guard let dict = result as? [String: AnyObject] else {
                print("数据格式错误")
                finished(isSuccess: false)
                return
            }
            
            // 存储用户信息
            
            self.account!.avatar_large = dict["avatar_large"] as? String
            self.account!.screen_name = dict["screen_name"] as? String
            
            print(self.accountPath)
            
            NSKeyedArchiver.archiveRootObject(self.account!, toFile: self.accountPath)
            
            finished(isSuccess: true)
        })
    }
}







